import express from 'express';
import { prisma } from '../service/mysql.js';
import { logger, dayjs } from '../tools/index.js';

const router = express.Router();

router.get('/funds', async (req, res, next) => {
    const accountNo = req.query.accountNo;
    const bookId = req.query.bookId;
    const month = req.query.month;
    const day = req.query.day;
    const tags = req.query.tags ? req.query.tags.split(',') : [];
    const page = req.query.page;
    const pageSize = req.query.pageSize || 20;

    if (!bookId) {
        return res.json({
            success: true,
            message: '',
            data: {
                current: page,
                pageSize: pageSize,
                totalPage: 0,
                total: 0,
                data: []
            }
        });
    }

    const queryTransactionIdList = [];
    if (tags.length > 0) {
      const transactionIdList = await prisma.t_transaction_tags.groupBy({
        by: ['transaction_id'],
        where: {
          book_id: bookId,
          tag: {
            in: tags
          }
        }
      });
      transactionIdList.forEach(row => queryTransactionIdList.push(row.transaction_id));
    }

    const whereRules = {
        book_id: bookId,
        AND: [{
            create_time: month ? {
                gte: dayjs(month, 'YYYY-MM').startOf('month').toDate(),
                lte: dayjs(month, 'YYYY-MM').endOf('month').toDate()
            } : undefined,
        }, {
            create_time: day ? {
                gte: dayjs(day, 'YYYY-MM-DD').startOf('date').toDate(),
                lte: dayjs(day, 'YYYY-MM-DD').endOf('date').toDate()
            } : undefined
        }, {
            id: queryTransactionIdList.length > 0 ? {
                in: queryTransactionIdList
            } : undefined
        }],
        OR: accountNo ? [
            {
                create_account_no: accountNo || undefined,
            },
            {
                from_account_no: accountNo || undefined,
            },
            {
                to_account_no: accountNo || undefined,
            }
        ] : undefined
    };
    const total = await prisma.t_transaction.count({
        where: whereRules
    })
    const funds = await prisma.t_transaction.findMany({
        where: whereRules,
        skip: (page - 1) * pageSize,
        take: parseInt(pageSize),
        orderBy: {
            id: 'desc'
        }
    });
    return res.json({
        success: true,
        message: '',
        data: {
            current: page,
            pageSize: pageSize,
            totalPage: Math.ceil(total / pageSize),
            total: total,
            data: funds
        }
    });
});

export default router;